/**
 * Created by Administrator on 2017/9/4.
 */
/**
 * 教师端直播组件
 * 通过获取cookie中的信息(courseId\username)建立rtcRoom
 */
define(function (require) {

    /***
     * 事件触发器
     * @returns {emit}
     * @constructor
     */
    function Emit() {
        var events = {};


        function emit() {

        }

        emit.prototype = {
            on: function (eventName, eventFn) {
                events[eventName] = events[eventName] || [];
                events[eventName].push(eventFn);
            },
            trigger: function (eventName, _) {
                for (var fn in events[eventName]) {
                    events[eventName][fn].apply(null, Array.prototype.slice.call(arguments, 1));
                }
            }
        }
        return new emit();
    }

    var $ = require("jquery");
    require("jquery.cookie");
    var userHandler = new require("userHandler").TeacherHandler();
    var liveRoom = null;
    var mediaStream = null;
    var ws = require("webSocketChannel")

    function init() {
        liveRoom = new require("liveRTC").RtcRoom({name: $.cookie("username")});
    }


    function requestOpen() {

        var that = this;

        userHandler.startLive($.cookie("courseId"), function () {
            liveRoom.openUserMedia(undefined, function (stream) {
                mediaStream = stream;
                console.warn("x")
                that.trigger("open", stream);
                console.warn("startLive");
                liveRoom.openMediaStream();
            });
            liveRoom.setWebSocketChannel(ws);
        });


    }

    function requestClose() {
        var that = this;

        userHandler.endLive($.cookie("courseId"), function () {
            console.log("endLive")
            that.trigger("closed");
        });

        /*

         写完再补充

         */

    }


    init();


    function allowMediaStreamTransferring() {
        liveRoom.openMediaStream();
    }

    function limitMediaStreamTransferring() {
        liveRoom.stopMediaStream();
    }


    function LiveRoomComponent() {

    }

    LiveRoomComponent.prototype = new Emit();
    LiveRoomComponent.prototype.requestOpen = requestOpen;
    LiveRoomComponent.prototype.requestClose = requestClose;
    return new LiveRoomComponent();

})